package com.zlp.socket;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @Author: zhulaiping
 * @Date: 2021/10/27 10:08
 */
public class SocketWebTest {

    public static void main(String[] args) throws IOException {

        int port = 8088;
        ServerSocket serverSocket = new ServerSocket(port);
        while (true){
            Socket socket = serverSocket.accept();
            new Thread(new WebHandler(socket)).start();
        }
    }

    static class WebHandler implements Runnable{

        private Socket socket;
        public WebHandler(Socket socket) {
            this.socket = socket;
        }

        @Override
        public void run() {
            try {
                BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));

                String[] strs = reader.readLine().split(" ");
                String path = strs[1].substring(1);
                System.out.println("接收到了请求，路径为："+path);
                OutputStream out = socket.getOutputStream();
                out.write("HTTP/1.1 200 OK\r\n".getBytes());
                out.write("Content-Type:text/html; charset=UTF-8\r\n".getBytes());
                // 必须要写入空行,否则浏览器不解析
                out.write("\r\n".getBytes());
                out.write(("收到了请求，路径为："+path).getBytes());
                new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
